package com.have.blog.web.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.have.blog.base.enums.BlogStatus;
import com.have.blog.base.wrapper.CommonPage;
import com.have.blog.base.wrapper.Wrapper;
import com.have.blog.model.mapper.BlogSubjectItemMapper;
import com.have.blog.model.mapper.BlogSubjectMapper;
import com.have.blog.model.models.BlogSubject;
import com.have.blog.model.models.BlogSubjectExample;
import com.have.blog.picture.service.PictureFeignApi;
import com.have.blog.utils.MyBeanUtils;
import com.have.blog.web.dto.BlogSubjectDto;
import com.have.blog.web.service.BlogSubjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@SuppressWarnings("all")
public class BlogSubjectServiceImpl  implements BlogSubjectService {
    @Autowired
    private BlogSubjectItemMapper subjectItemMapper;
    @Autowired
    private BlogSubjectMapper subjectMapper;
    @Autowired
    private PictureFeignApi pictureFeignApi;

    @Override
    public Wrapper<CommonPage<BlogSubjectDto>> getPgeList(Integer pageNum, Integer pageSize) {
        Page<Object> page = PageHelper.startPage(pageNum, pageSize);
        BlogSubjectExample example = new BlogSubjectExample();
        example.createCriteria()
                .andStatusEqualTo(BlogStatus.ENABLE.getStatus());
        example.setOrderByClause("sort desc");
        List<BlogSubject> subjectList = subjectMapper.selectByExample(example);
        List<BlogSubjectDto> resultList = MyBeanUtils.copyListProperties(subjectList, BlogSubjectDto::new);
        CommonPage<BlogSubjectDto> commonPage = CommonPage.restPage(resultList);
        commonPage.setPageSize(page.getPageSize());
        commonPage.setTotal(page.getTotal());
        commonPage.setPageNum(page.getPageNum());

        List<Integer> uids = new ArrayList<>();
        resultList.forEach(item -> {
            if (item.getCoverPictureUid() != null) {
                uids.add(item.getCoverPictureUid());
            }
        });
        if (!CollectionUtils.isEmpty(uids)) {
            Wrapper<Map<Integer, String>> wrapper = pictureFeignApi.getPicturesUrl(uids);
            if (wrapper.isSuccess()) {
                Map<Integer, String> picMap = wrapper.getData();
                for (BlogSubjectDto blogSubjectDto : resultList) {
                    blogSubjectDto.setPhotoUrl(picMap.get(blogSubjectDto.getCoverPictureUid()));
                }
            }
        }
        return Wrapper.success(commonPage);
    }
}

